﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Globalization;

namespace Wicresoft.SMS.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("favicon.ico");

            routes.MapRoute(
                null,
                "report/{action}",
                new { controller = "Report" }
            );

            routes.MapRoute(
                 null,
                 "manage/group/{category}",
                 new { controller = "Manage", action = "Group", category = UrlParameter.Optional }
             );


            routes.MapRoute(
                 null,
                 "manage/users/{category}",
                 new { controller = "Manage", action = "Users", category = UrlParameter.Optional }
             );


            routes.MapRoute(
                 null,
                 "history/failed/{category}",
                 new { controller = "History", action = "Failed", category = UrlParameter.Optional }
             );

            routes.MapRoute(
                 null,
                 "history/delivered/{category}",
                 new { controller = "History", action = "Delivered", category = UrlParameter.Optional }
             );

            routes.MapRoute(
                 null,
                 "history/pending/{category}",
                 new { controller = "History", action = "Pending", category = UrlParameter.Optional }
             );

            routes.MapRoute(
               null,
               "help/{category}",
               new { controller = "Common", action = "Help", category = UrlParameter.Optional }
           );

            routes.MapRoute(
                 null,
                 "address/index",
                 new { controller = "Address", action = "Index" }
             );

            routes.MapRoute(
                null,
                "address/group",
                new { controller = "Address", action = "Group" }
            );
            routes.MapRoute(
                 null,
                 "template/index",
                 new { controller = "Template", action = "Index" }
             );

            routes.MapRoute(
                 null,
                 "send/index",
                 new { controller = "Send", action = "Index" }
             );


            routes.MapRoute(
                 null,
                 "home/setting",
                 new { controller = "Home", action = "Setting" }
             );

            routes.MapRoute(
                 null,
                 "home/index",
                 new { controller = "Home", action = "Index" }
             );

            routes.MapRoute(
                 null,
                 "home",
                 new { controller = "Home", action = "Index" }
             );

            routes.MapRoute(
                null,
                "error",
                new { controller = "Home", action = "ErrorPage" }
            );

            routes.MapRoute(
                 null,
                 "login",
                 new { controller = "Account", action = "LogIn" }
             );

            routes.MapRoute(
                null,
                "logout",
                new { controller = "Account", action = "logout" }
            );

            routes.MapRoute(
               null,
               "certification",
               new { controller = "CommonController", action = "Certification" }
           );

            routes.MapRoute(
               null,
               "olplugin",
               new { controller = "CommonController", action = "OlPlugin" }
           );
                        
            routes.MapRoute(
                null, // Route name
                "{controller}/{action}", // URL with parameters
                new { controller = "Home", action = "Index" } // Parameter defaults
            );
                       
        }

        protected void Application_Start()
        {
            //AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            RegisterGlobalizationRoutes();

            ControllerBuilder.Current.SetControllerFactory(new CustomControllerFactory());
        }


               /// <summary>
        /// copy and add {ci}/ before url of each non-IgnoreRouteInternal route , and register them before original route
        /// </summary>
        private void RegisterGlobalizationRoutes()
        {

            if (RouteTable.Routes == null)
                return;

            RouteCollection rc = new RouteCollection();

            //skip IgnoreRouteInternal
            var routes = RouteTable.Routes.Where(p => (p.GetType().Name != "IgnoreRouteInternal"));

            int insertpoint = RouteTable.Routes.Count() - routes.Count();

            foreach (var r in routes)
            {
                Route item = (r as Route);
                Route newitem = new Route(
                    //string.Format(@"{ci}/{0}",item.Url),
                    @"{ci}/" + item.Url,
                    new MvcRouteHandler());
                newitem.Defaults = new RouteValueDictionary(item.Defaults);

                newitem.Constraints = new RouteValueDictionary(item.Constraints);
                newitem.Constraints.Add("ci", new CulturePrefixRule());

                newitem.DataTokens = new RouteValueDictionary();
                newitem.DataTokens["Namespaces"] = item.DataTokens["Namespaces"];
                newitem.DataTokens["area"] = item.DataTokens["area"];
                newitem.DataTokens["UseNamespaceFallback"] = item.DataTokens["UseNamespaceFallback"];
                rc.Add(newitem);
            }
            foreach (var c in rc)
            {
                RouteTable.Routes.Insert(insertpoint, c);
                insertpoint += 2;
            }
        }

        private class CulturePrefixRule : IRouteConstraint
        {
            IEnumerable<string> cultureConllection = CultureInfo.GetCultures(CultureTypes.SpecificCultures).Select(p => p.Name.ToLower());
            public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
            {
                if (values[parameterName] != null)
                    return cultureConllection.Contains(values[parameterName].ToString().ToLower());
                else
                    return false;
            }
        }
    }
}